import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';

// 定义全局变量
class GlobalState {
  static ValueNotifier<bool> isLoggedIn = ValueNotifier(false);
  static String avatarPath = 'lib/assets/tx.png';
  static String username = '未登录';
  static int followers = 0;
  static int fans = 0;
  static int likes = 0;
  static int sameShot = 0;

  // 添加重置方法
  static void reset() {
    isLoggedIn.value = false;
    avatarPath = 'lib/assets/tx.png';
    username = '未登录';
    followers = 0;
    fans = 0;
    likes = 0;
    sameShot = 0;
  }
}


class SmsController {  
  Future<void> verifyCodeAndLogin(String phoneNumber, String code, BuildContext context) async {  
    final response = await http.post(  
      // 后端接口，替换你的后端接口
      Uri.parse('http://43.134.218.65:5004/verify_code'),  
      headers: <String, String>{  
        'Content-Type': 'application/json',  
      },  
      body: jsonEncode(<String, String>{  
        'phone_number': phoneNumber,  
        'code': code,  
      }),  
    );  
  
    if (response.statusCode == 200) {  
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('登录成功')),
      );

      // 更新全局状态
      GlobalState.isLoggedIn.value = true;
      GlobalState.avatarPath = 'lib/assets/logo.png';
      GlobalState.username = 'user';
      GlobalState.followers = 4;
      GlobalState.fans = 3;
      GlobalState.likes = 2;
      GlobalState.sameShot = 1;

      // 关闭上拉框并回到主页面
      Navigator.pop(context);
    } else {  
      ScaffoldMessenger.of(context).showSnackBar(  
        SnackBar(content: Text('手机号或验证码错误')),  
      );  
    }  
  }
  
  Future<void> sendCode(String phoneNumber, BuildContext context, Function updateState) async {  
    if (phoneNumber.length == 11) {  
      final response = await http.post(
        // 后端接口，替换你的后端接口
        Uri.parse('http://43.134.218.65:5004/send_verification_sms'),  
        headers: <String, String>{  
          'Content-Type': 'application/json',  
        },  
        body: jsonEncode(<String, String>{  
          'phone_number': phoneNumber,  
        }),  
      );  
  
      if (response.statusCode == 200) {  
        updateState();  
        ScaffoldMessenger.of(context).showSnackBar(  
          SnackBar(content: Text('验证码已成功发送')),  
        );  
      } else {  
        ScaffoldMessenger.of(context).showSnackBar(  
          SnackBar(content: Text('验证码发送失败')),  
        );  
      }  
    } else {  
      ScaffoldMessenger.of(context).showSnackBar(  
        SnackBar(content: Text('手机号格式错误')),  
      );  
    }  
  }
}
